<script setup lang="ts">
import vueDanmaku from 'vue3-danmaku'
import commentApi from '@/service/api/comment'

type PropsState = {
  pid: number | string
  isOpenComment?: boolean
}
const props = withDefaults(defineProps<PropsState>(), {
  isOpenComment: false,
  pid: ''
})
const danmus = ref([])
const colorList = ref([
  'rgb(204,255,255)',
  'white',
  'rgb(204,255,204)',
  'white',
  'rgb(0,255,255)',
  'white',
  'rgb(255,204,255)',
  'pink'
])
// 生成随机颜色的函数
const getRandomColor = () => {
  const color = colorList.value[Math.floor(Math.random() * 8)]
  return color
}

const init = async () => {
  const { data } = await commentApi.list({
    current: 1,
    size: 10,
    type: 4,
    photoId: props.pid
  })
  danmus.value = data
}
init()
</script>

<template>
  <div
    v-if="danmus.length > 0"
    class="danmaku"
    :class="{ 'danmaku-open': isOpenComment }"
  >
    <vue-danmaku
      style="height: 100px; width: 800px"
      ref="danmaku"
      v-model:danmus="danmus"
      :isSuspend="true"
      :top="20"
      useSlot
      loop
      :speeds="100"
      :channels="12"
    >
      <template v-slot:dm="{ danmu }">
        <div class="danmaku-name">
          <span class="bullet-item" :style="{ color: getRandomColor() }">
            <img :src="danmu.userInfo.avatar" alt="" />
            {{ danmu.content }}
          </span>
        </div>
      </template>
    </vue-danmaku>
  </div>
</template>

<style scoped lang="scss">
.danmaku {
  position: fixed;
  z-index: 10;
  top: 20px;
  width: 800px;
  height: 100rpx;
  left: 50%;
  transform: translateX(-50%);
  transition: all 0.3s;

  &-open {
    transform: translateX(calc(-50% - 150px));
  }

  .bullet-item {
    white-space: nowrap;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 30px;
    height: 30px;
    font-size: 16px;
    color: #ffffff;
    line-height: 30px;
    padding-right: 20px;
    display: flex;
    cursor: pointer;
  }

  img {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin-right: 10px;
  }
}
</style>
